package com.xbongbong.pro.statistic.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.BiConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.SizeConstant;
import com.xbongbong.paas.domain.entity.PaasStageEntity;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.BIProductReformEnum;
import com.xbongbong.paas.enums.BiRelTableEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.DistributorMarkHelp;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.pojo.StageFindPojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.MathUtil;
import com.xbongbong.paas.toolbox.util.RegexUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.paas.util.ItemUtil;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.domain.entity.BiProWareEntity;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.domain.entity.LabelEntity;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.IntervalTypeEnum;
import com.xbongbong.pro.enums.errorcodes.BiErrorCodeEnum;
import com.xbongbong.pro.label.pojo.LabelPojo;
import com.xbongbong.pro.service.stage.StageFindStrategy;
import com.xbongbong.pro.service.stage.factory.StageFindFactory;
import com.xbongbong.pro.service.toolbox.statistic.help.FormHelp;
import com.xbongbong.pro.statistic.manager.feign.StatisticsWorkOrderV2FeignClient;
import com.xbongbong.pro.statistic.pojo.FieldAnalysisPojo;
import com.xbongbong.pro.statistic.pojo.SlaveSourcePojo;
import com.xbongbong.pro.statistic.pojo.dto.FieldAnalysisDTO;
import com.xbongbong.pro.statistic.pojo.vo.FieldAnalysisVO;
import com.xbongbong.pro.statistic.result.pojo.FieldAttrPojo;
import com.xbongbong.pro.statistic.service.BiProWareService;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.CommunicatePlanUserEntity;
import com.xbongbong.saas.domain.entity.CustomerStageEntity;
import com.xbongbong.saas.domain.entity.PaymentTaskUserEntity;
import com.xbongbong.saas.domain.entity.ProductCategoryEntity;
import com.xbongbong.saas.domain.entity.SaleStageEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.domain.entity.WorkOrderStageEntity;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.dictionary.DictionaryEnum;
import com.xbongbong.saas.enums.dictionary.OrderStatusEnum;
import com.xbongbong.saas.enums.subform.SubFormTransferEnum;
import com.xbongbong.saas.help.FundHelp;
import com.xbongbong.saas.model.CommunicatePlanUserModel;
import com.xbongbong.saas.model.CustomerStageModel;
import com.xbongbong.saas.model.DataDictionaryModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.LabelModel;
import com.xbongbong.saas.model.PaymentTaskUserModel;
import com.xbongbong.saas.model.ProductCategoryModel;
import com.xbongbong.saas.model.SaleStageModel;
import com.xbongbong.saas.model.WorkOrderStageModel;
import com.xbongbong.saas.util.FundUtil;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * 字段解析
 * @author zhouwq
 * @date 2019/4/23 18:57
 */
@Component
public class FieldAnalysisHelp {
    private static final Logger LOG = LoggerFactory.getLogger(FieldAnalysisHelp.class);
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private CustomHelp customHelp;
    @Resource
    private UserModel userModel;
    @Resource
    private ProductCategoryModel productCategoryModel;
    @Resource
    private CustomerStageModel customerStageModel;
    @Resource
    private SaleStageModel saleStageModel;
    @Resource
    private DataDictionaryModel dataDictionaryModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private WorkOrderStageModel workOrderStageModel;
    @Resource
    private CommunicatePlanUserModel communicatePlanUserModel;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private BiProWareService biProWareService;
    @Resource
    private PaymentTaskUserModel paymentTaskUserModel;
    @Resource
    private FormHelp formHelp;
    @Resource
    private LabelModel labelModel;
    @Resource
    private FundHelp fundHelp;
    @Resource
    private DistributorMarkHelp distributorMarkHelp;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private StatisticsWorkOrderV2FeignClient statisticsWorkOrderV2FeignClient;

    /**
     * 负责人/协同人团队字段解析
     * @param fieldAnalysisPojo 字段解析实体类
     * @return 结果值
     * @author zhouwq
     * @date 2019/4/22 15:35
     * @throws XbbException error
     */
    public Map<String, String> teamAnalysis(FieldAnalysisPojo fieldAnalysisPojo) throws XbbException {
        Map<String, String> results = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        SearchRequest searchRequest = new SearchRequest();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        chartDataTeam(fieldAnalysisPojo.getChartEntity(), sourceBuilder, boolQueryBuilder, searchRequest);
        FieldAttrPojo field = fieldAnalysisPojo.getField();
        Integer businessType = field.getBusinessType();
        //获取团队字段映射
        IndexTypeEnum indexTypeEnum = indexTypeModel.getTeamIndexType(fieldAnalysisPojo.getChartEntity().getCorpid(), businessType);
        String isMainAttr = SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(indexTypeEnum, ParameterConstant.IS_MAIN);
        String idName = SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(indexTypeEnum, StringConstant.DATA_ID);
        String userNameAttr = SubFormTransferEnum.getEsAttrByIndexTypeAndDbAttr(indexTypeEnum, "userName");
        userNameAttr = userNameAttr.replaceAll(".keyword", "").replaceAll("data.", "");
        String dataIdAttr = idName.replaceAll(".keyword", "").replaceAll("data.", "");

        boolQueryBuilder.filter(termsQuery(idName, fieldAnalysisPojo.getValuesResult()));
        if (FieldTypeEnum.COUSERID.getType().equals(field.getFieldType())) {
            boolQueryBuilder.filter(termQuery(isMainAttr, 0));
        } else {
            boolQueryBuilder.filter(termQuery(isMainAttr, 1));
        }
        EsUtil.setPage(sourceBuilder, 1, SizeConstant.PAGE_SIZE);
        searchRequest.source(sourceBuilder);
        List<JSONObject> esList= xbbElasticsearchRestTemplate.getScrollListForExport(JSONObject.class, searchRequest);
        if(esList.size() > 0){
            Map<String, Set<JSONObject>> dataIdToList = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (JSONObject e : esList) {
                JSONObject data = e.getJSONObject("data");
                String dataId = data.getString(dataIdAttr);
                Set<JSONObject> objects;
                if (dataIdToList.containsKey(dataId)) {
                    objects = dataIdToList.get(dataId);
                    objects.add(e);
                } else {
                    objects = new HashSet<>();
                    objects.add(e);
                    dataIdToList.put(dataId, objects);
                }
            }
            for (Map.Entry<String, Set<JSONObject>> entry : dataIdToList.entrySet()) {
                String key = entry.getKey();
                Set<JSONObject> value = entry.getValue();
                StringBuilder userNames = new StringBuilder();
                //多负责人/协同人字符串组装
                for (JSONObject esEntity : value) {
                    if (esEntity != null) {
                        JSONObject data = esEntity.getJSONObject("data");
                        userNames.append(data.getString(userNameAttr)).append(",");
                    }
                }
                String userName = "";
                if (userNames.length() > 0) {
                    userName = userNames.substring(0, userNames.length() - 1);
                }
                results.put(key, userName);
            }
        }
        return results;
    }

    /**
     *
     * @param fieldAnalysisPojo 字段解析实体类
     * @author zhouwq
     * @date 2019/4/24 9:00
     */
    public Map<String, String> userAnalysis(FieldAnalysisPojo fieldAnalysisPojo){
        List<String> userIds = new ArrayList<>();
        List<String> values = fieldAnalysisPojo.getValuesResult();
        values.forEach(value -> {
            if(value.contains(StringConstant.COMMA)){
                String[] valueArray = value.split(StringConstant.COMMA);
                userIds.addAll(Arrays.asList(valueArray));
            }else{
                userIds.add(value);
            }
        });
        List<UserEntity> userEntities = userModel.getUserNamesAllByIdIn(fieldAnalysisPojo.getCorpid(), userIds);
        Map<String, String> results = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userEntities.forEach((UserEntity userEntity) -> results.put(userEntity.getUserId(), userEntity.getName()));
        return results;
    }

    /**
     * 产品分类字段解析
     * @param fieldAnalysisPojo 字段解析实体类
     * @author zhouwq
     * @date 2019/4/24 9:00
     */
    public Map<String, String> categoryAnalysis(FieldAnalysisPojo fieldAnalysisPojo){
        List<Long> idIn = new ArrayList<>();
        List<String> values = fieldAnalysisPojo.getValuesResult();
        values.forEach(value -> {
            if ("".equals(value)) {
                return;
            }
            idIn.add(Math.round(Double.parseDouble(value)));
        });
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid", fieldAnalysisPojo.getCorpid());
        map.put("idIn", idIn);
        map.put("del", DelEnum.NORMAL.getDel());
        List<ProductCategoryEntity> entity = productCategoryModel.findEntitys(map);

        Map<String, String> results = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        entity.forEach(e -> results.put(e.getId().toString(), e.getName()));
        return results;
    }

    /**
     * combo类型下的字段解析
     * @param fieldAnalysisPojo 字段解析实体类
     * @author zhouwq
     * @date 2019/4/24 9:00
     */
    public Map<String, String> comboAnalysis(FieldAnalysisPojo fieldAnalysisPojo){
        FieldAttrPojo field = fieldAnalysisPojo.getField();
        List<String> values = fieldAnalysisPojo.getValuesResult();
        String corpId = fieldAnalysisPojo.getCorpid();
        Integer businessType = field.getBusinessType();
        String saasAttr = field.getSaasAttr();
        String originalAttr = field.getOriginalAttr();
        Long formId = field.getFormId();
        Map<String, String> results = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<ItemPoJo> itemPoJos = new ArrayList<>();
        //销售阶段
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.equals(SalesOpportunityEnum.SALE_STAGE.getSaasAttr(),saasAttr) || Objects.equals(CustomerManagementEnum.CUSTOMER_STAGE.getSaasAttr(),saasAttr)) {
            List<String> codeIn = new ArrayList<>();
            values.forEach(e -> {
                if(!Objects.equals(null, e) && !Objects.equals("", e)){
                    codeIn.add(e);
                }
            });
            params.put("corpid", corpId);
            params.put("del",0);
            params.put("formId",formId);
            params.put("codeIn",codeIn);
            if (Objects.equals(SalesOpportunityEnum.SALE_STAGE.getSaasAttr(),saasAttr)) {
                List<SaleStageEntity> saleStageEntities = saleStageModel.findEntitys(params);
                saleStageEntities.forEach((SaleStageEntity saleStageEntity) -> results.put(saleStageEntity.getCode(), saleStageEntity.getName()));
                return results;
            } else if (Objects.equals(CustomerManagementEnum.CUSTOMER_STAGE.getSaasAttr(),saasAttr)) {
                List<CustomerStageEntity> customerStageEntities = customerStageModel.findEntitys(params);
                customerStageEntities.forEach((CustomerStageEntity customerStageEntity) -> results.put(customerStageEntity.getCode() ,customerStageEntity.getName()));
                return results;
            }
        }
        try {
            //原逻辑只判断saasAttr，数据集增加处理：子产品用originalAttr，产品要结合businessType、originalAttr（数据集无saasAttr - 合并节点的saasAttr不准确）
            boolean productUnit = Objects.equals(ProductEnum.UNIT.getSaasAttr(), saasAttr) || (BIProductReformEnum.getProductSubBusList().contains(businessType) && Objects.equals(SelectProductEnum.UNIT.getAttr(), originalAttr)) || (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(ProductEnum.UNIT.getAttr(), originalAttr));
            //资金账户对应saasAttr
            List<String> fundAccountSaasAttrList = FundUtil.getFundAccountSaasAttrList();
            //在tb_data_dictionary表内   经过转换子表单的parentAttr也可能转为电话的attr=subForm_1
            if (Objects.equals(CustomerManagementEnum.TYPE.getSaasAttr(),saasAttr) && Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),businessType)  && !Objects.equals(CustomerManagementEnum.PHONE.getAttr(),field.getParentAttr()) && !(field.getParentAttr() != null && field.getParentAttr().contains(FieldTypeEnum.SUB_FORM.getEsalias()) )) {
                //字段是类型，但是不在客户电话的子表单内，客户电话的子表单类型也是type
                itemPoJos = dataDictionaryModel.getArrayList(DictionaryEnum.CUSTOMER_STATUS, corpId, formId);
            } else if (Objects.equals(ContractEnum.STATUS.getSaasAttr(),saasAttr) && Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(),businessType)) {
                //经销商合并 订货单和合同的businessType相同   36630、40620
                Integer distributorMark = distributorMarkHelp.getDistributorMark(formId, corpId);
                if(Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode())){
                    return OrderStatusEnum.orderStatusMap();
                }
                itemPoJos = dataDictionaryModel.getArrayList(DictionaryEnum.CONTRACT_STATUS, corpId, formId);
            } else if (Objects.equals(XbbRefTypeEnum.SLA_LOG.getCode(), businessType) && Objects.equals("slaRuleName", saasAttr)) {
                FieldAnalysisDTO fieldAnalysisDTO = new FieldAnalysisDTO(fieldAnalysisPojo);
                BeanUtil.copyProperties(fieldAnalysisPojo, fieldAnalysisDTO);
                XbbResponse<FieldAnalysisVO> response = statisticsWorkOrderV2FeignClient.getSlaRuleNameMap(fieldAnalysisDTO, LocaleContextHolder.getLocale().toString());
                Map<String, String> slaRuleNameMap = response.getResult().getRes();
                itemPoJos = transferItemPojo(slaRuleNameMap);
            } else if (Objects.equals(XbbRefTypeEnum.SLA_LOG.getCode(), businessType) && Objects.equals("formName", saasAttr)) {
                FieldAnalysisDTO fieldAnalysisDTO = new FieldAnalysisDTO(fieldAnalysisPojo);
                BeanUtil.copyProperties(fieldAnalysisPojo, fieldAnalysisDTO);
                XbbResponse<FieldAnalysisVO> response = statisticsWorkOrderV2FeignClient.getWorkOrderFormNameMap(fieldAnalysisDTO, LocaleContextHolder.getLocale().toString());
                Map<String, String> formNameMap = response.getResult().getRes();
                itemPoJos = transferItemPojo(formNameMap);
            } else if (Objects.equals(XbbRefTypeEnum.WORK_ORDER_V2.getCode(), businessType) && Objects.equals("currentPhase", saasAttr)){
                FieldAnalysisDTO fieldAnalysisDTO = new FieldAnalysisDTO(fieldAnalysisPojo);
                BeanUtil.copyProperties(fieldAnalysisPojo, fieldAnalysisDTO);
                XbbResponse<FieldAnalysisVO> response = statisticsWorkOrderV2FeignClient.getNodeNameMap(fieldAnalysisDTO, LocaleContextHolder.getLocale().toString());
                Map<String, String> nodeNameMap = response.getResult().getRes();
                itemPoJos = transferItemPojo(nodeNameMap);
            }else if (fundAccountSaasAttrList.contains(saasAttr)) {
                itemPoJos = proFormHelp.handleFundAccountItems(corpId, businessType);
            } else if (productUnit) {
                itemPoJos = formHelp.getProductBaseItems(corpId);
            } else if (Objects.equals(SelectProductEnum.UNIT.getSaasAttr(), saasAttr)) {
                itemPoJos = formHelp.getBusinessUnitItems(corpId);
            } else {
                itemPoJos = field.getItems();
            }
        } catch (Exception e) {
            LOG.error("valueAnalysis获取数据字典出错", e);
        }
        for (String value : values) {
            if (itemPoJos != null && itemPoJos.size() > 0) {
                List<ItemPoJo> itemResult = itemPoJos.stream().filter(itemPoJo -> Objects.equals(value, itemPoJo.getValue().toString())).collect(Collectors.toList());
                if (itemResult.size() > 0) {
                    results.put(value, itemResult.get(0).getText());
                } else {
                    boolean uuIdFlag = !ItemUtil.isUUID(value) && (!RegexUtil.isOnePositiveInt(value) || !Objects.equals(field.getIsRedundant(), 0));
                    if (uuIdFlag) {
                        results.put(value, value);
                    }
                }
            }
        }
        return results;
    }

    /**
     * Map 转 ItemPojo
     * @param slaRuleNameMap
     * @return
     */
    private List<ItemPoJo> transferItemPojo(Map<String, String> slaRuleNameMap) {
        List<ItemPoJo> res = new ArrayList<>(slaRuleNameMap.size());
        slaRuleNameMap.forEach((id,name)->{
            ItemPoJo item = new ItemPoJo();
            item.setCode(id);
            item.setText(name);
            item.setValue(id);
            res.add(item);
        });
        return res;
    }

    /**
     * Paas自定义字段 下拉多选/复选框 解析
     * @param fieldAnalysisPojo 字段解析实体类
     * @return 结果值
     * @author zhouwq
     * @date 2019/5/23 20:15
     */
    public Map<String, String> customListAnalysis(FieldAnalysisPojo fieldAnalysisPojo){
        List<ItemPoJo> itemPoJos = fieldAnalysisPojo.getField().getItems();
        Map<String, String> results = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        itemPoJos.forEach(itemPoJo -> results.put(itemPoJo.getValue().toString(), itemPoJo.getText()));
        return results;
    }

    /**
     * 工单阶段 字段解析
     * @param fieldAnalysisPojo 字段解析实体类
     * @author zhouwq
     * @date 2019/5/20 14:46
     */
    public Map<String, String> workOrderStageAnalysis(FieldAnalysisPojo fieldAnalysisPojo){
        Map<String, String> results = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        try{
            List<String> values = fieldAnalysisPojo.getValuesResult();
            List<Long> idIn = new ArrayList<>();
            values.forEach(value -> idIn.add(Long.parseLong(value)));
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("corpid", fieldAnalysisPojo.getCorpid());
            params.put("idIn", idIn);
            List<WorkOrderStageEntity> entities = workOrderStageModel.findEntitys(params);
            entities.forEach(e -> results.put(e.getId().toString(), e.getName()));
            return results;
        }catch (Exception e){
            LOG.error("workOrderStageAnalysis报错",e);
            return results;
        }
    }

    /**
     * 部门字段解析
     * @param fieldAnalysisPojo 字段解析实体类
     * @return 结果值
     * @author zhouwq
     * @date 2019/5/22 13:49
     */
    public Map<String, String> departmentAnalysis(FieldAnalysisPojo fieldAnalysisPojo){
        Set<Long> depIdIn = new HashSet<>();
        List<String> values = fieldAnalysisPojo.getValuesResult();
        for(String value : values) {
            if(value != null && !"".equals(value)) {
                if (value.contains(StringConstant.COMMA)) {
                    String[] valuesArray = value.split(StringConstant.COMMA);
                    for (String s : valuesArray) {
                        try {
                            depIdIn.add(Long.parseLong(s));
                        } catch (NumberFormatException e) {
                            LOG.error("long类型数据转换格式错误,chartID = " + fieldAnalysisPojo.getChartEntity().getId(), e);
                        }
                    }
                } else {
                    try{
                        depIdIn.add(Long.parseLong(value));
                    }catch (NumberFormatException e){
                        LOG.error("long类型数据转换格式错误,chartID = " + fieldAnalysisPojo.getChartEntity().getId(), e);
                    }
                }
            }
        }
        List<DepartmentEntity> departmentEntityList = departmentModel.getDepartmentNamesByIds(fieldAnalysisPojo.getCorpid(),depIdIn, true);
        Map<String, String> result = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        departmentEntityList.forEach((DepartmentEntity departmentEntity) -> result.put(departmentEntity.getId().toString(), departmentEntity.getName()));
        return result;
    }

    /**
     * Saas字段-下拉复选和复选框组字段解析
     * @param fieldAnalysisPojo 字段解析实体类
     * @return 结果值
     */
    public Map<String, String> executorAnalysis(FieldAnalysisPojo fieldAnalysisPojo){
        Map<String, Object> param = new HashMap<>(3);
        param.put("corpid",fieldAnalysisPojo.getCorpid());
        param.put("del",0);
        param.put("planIdIn",fieldAnalysisPojo.getValuesResult());
        Map<String, String> result = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Integer businessType = fieldAnalysisPojo.getBusinessType();
        FieldAttrPojo field = fieldAnalysisPojo.getField();
        if (Objects.equals(businessType, XbbRefTypeEnum.COMMUNICATE_PLAN.getCode())) {
            List<CommunicatePlanUserEntity> communicatePlanUserEntities = communicatePlanUserModel.findEntitys(param);
            for (CommunicatePlanUserEntity e : communicatePlanUserEntities) {
                result.put(e.getDataId().toString(), e.getUserName());
            }
        } else if (Objects.equals(businessType, XbbRefTypeEnum.PAYMENT_TASK.getCode())) {
            List<PaymentTaskUserEntity> entitys = paymentTaskUserModel.findEntitys(param);
            for (UserTeamEntity e : entitys) {
                result.put(e.getDataId().toString(), e.getUserName());
            }
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) && "settlementMethod".equals(field.getSaasAttr())){
            List<ItemPoJo> items = field.getItems();
            items.forEach(item->{
                result.put(item.getValue().toString(),item.getText());
            });
        }
        return result;
    }

    /**
     * 时间字段解析
     * @param fieldAnalysisPojo 字段解析实体类
     * @return 结果值
     */
    public Map<String, String> timeAnalysis(FieldAnalysisPojo fieldAnalysisPojo){
        Map<String, String> results = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        FieldAttrPojo field = fieldAnalysisPojo.getField();
        List<String> values = fieldAnalysisPojo.getValuesResult();
        String chosenDateType = field.getChosenDateType();
        String dateGroupType = field.getDateGroupType();
        // 非钻取模式下，以设置的数据格式为主
        if (StringUtil.isEmpty(chosenDateType)) {
            // 未设置时采用默认格式
            chosenDateType = field.getDateType();
        }
        // 行列分组字段的时候，以分组时间格式为主
        if (Objects.nonNull(dateGroupType) && fieldAnalysisPojo.getIsGroupField()) {
            IntervalTypeEnum intervalTypeEnum = IntervalTypeEnum.getByFormatStr(dateGroupType);
            chosenDateType = intervalTypeEnum.getDateFormat();
        }
        for (String time : values) {
            //为啥要单独搞个变量做key，是因为科学计数法值要变成数字的格式，但是外面做映射还是根据科学计数法的值去
            String keyTime = time;
            if(StringUtil.isEmpty(time)){
                continue;
            }
            //代表是科学计数法
            if (time.contains("E")) {
                time = MathUtil.getScientificNotationValue(time);
            }
            // 时间长度
            int dateLength = 10;
            //时间类型
            int size = time.length();
            if (size > dateLength) {
                results.put(time, DateUtil.getStringByDateGroup(Long.valueOf(time), chosenDateType));
            } else {
                String dateVal;
                //这里加判断是因为，ck库中的时间为0经过函数转换之后会变成4294938496，因此这里额外判断一下
                if(Objects.equals(StringConstant.UNIX_0_FOR_CK,time) || Objects.equals(StringConstant.ZERO,time)){
                    dateVal = "";
                }else{
                    long longTime = Long.valueOf(time);
                    if (longTime != -28800000 && longTime != 28800000 && longTime != 0) {
                        longTime = longTime * 1000L;
                    }
                    dateVal = DateUtil.getStringByDateGroup(longTime, chosenDateType);
                }
                results.put(keyTime, dateVal);
            }
        }
        return results;
    }

    /**
     * 开关类型字段解析
     * @param fieldAnalysisPojo 字段解析实体类
     * @return result
     */
    public Map<String, String> switchAnalysis(FieldAnalysisPojo fieldAnalysisPojo){
        Map<String, String> results = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        try{
            List<String> values = fieldAnalysisPojo.getValuesResult();
            values.forEach(e -> {
                try {
                    Double var1 = Double.valueOf(e);
                    String valueString = Objects.equals(1.0, var1) ? "是" : "否";
                    results.put(e, valueString);
                } catch (Exception e1) {
                    results.put(e, "否");
                }
            });
            return results;
        }catch (Exception e){
            LOG.error("workOrderStageAnalysis报错",e);
            return results;
        }
    }


    /**
     * 根据dataID查询协同人/负责人团队ID
     * @param chartEntity 图表实体
     * @param sourceBuilder api
     * @param boolQueryBuilder 筛选
     * @param searchRequest 查询语句封装
     * @throws XbbException error
     * @author zhouwq
     * @date 2019/4/22 14:37
     */
    private void chartDataTeam(ChartEntity chartEntity, SearchSourceBuilder sourceBuilder, BoolQueryBuilder boolQueryBuilder, SearchRequest searchRequest) throws XbbException{
        boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID,chartEntity.getCorpid()));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL,0));
        sourceBuilder.query(boolQueryBuilder);
        //获取主数据源和从数据源
        JSONObject driverSourcesObject = chartEntity.getDriverSources();
        SlaveSourcePojo driverSourcePojo = JSON.toJavaObject(driverSourcesObject, SlaveSourcePojo.class);
        JSONArray slaveSourcesObject = chartEntity.getSlaveSources();
        //数据表顺序
        //从数据表，多表数据源
        if(Objects.equals(chartEntity.getMuti(),0)) {
            //主数据表
            boolean hasSecondSlave = false;
            if (slaveSourcesObject.size() > 1) {
                hasSecondSlave = true;
            }
            //把 主数表 先装入列表
            List<SlaveSourcePojo> slaveSourceList = slaveSourcesObject.toJavaList(SlaveSourcePojo.class);
            BiRelTableEnum biRelTableEnum = customHelp.getBiRelTableEnum(hasSecondSlave, slaveSourceList, driverSourcePojo.getBusinessType(), driverSourcePojo.getSaasMark());
            if(CollectionsUtil.isNotEmpty(slaveSourceList)) {
                List<BiProWareEntity> list = biProWareService.getBiProWareEntities(chartEntity);
                if(!list.isEmpty()){
                    if(Objects.equals(list.get(0).getIsDone(),0)){
                        throw  new XbbException(BiErrorCodeEnum.API_ERROR_241013);
                    }
                    boolQueryBuilder.filter(termQuery(BiConstant.WAREHOUSE_ID,list.get(0).getId()));
                }
            }
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,biRelTableEnum.getType()));
            searchRequest.indices(biRelTableEnum.getIndex());
        }else {
            //单表
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(chartEntity.getCorpid(), driverSourcePojo.getBusinessType(), driverSourcePojo.getSaasMark());
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,ElasticConstant.TEAM_TYPE));
            searchRequest.indices(indexTypeEnum.getIndex());
        }
    }

    /**
     * 标签处理
     *  把id转化成为实体
     * @param fieldAnalysisPojo
     * @return
     */
    public Map<String, String> labelAnalysis(FieldAnalysisPojo fieldAnalysisPojo) {
        Map<String, String> results = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        try{
            List<String> values = fieldAnalysisPojo.getValuesResult();
            List<Long> idIn = new ArrayList<>();
            for (String value : values) {
                List<String> strings = StringUtil.toStringList(value, StringConstant.COMMA);
                if (CollectionsUtil.isNotEmpty(strings)) {
                    strings.forEach(string -> {
                        if (StringUtil.isNotEmpty(string)) {
                            Long id  = Long.parseLong(string);
                            idIn.add(id);
                        }
                    });
                }
            }
            if (idIn.size()>0) {
                List<LabelEntity> labelEntities = labelModel.getByLabelIds(idIn, fieldAnalysisPojo.getCorpid());
                labelEntities.forEach(item->{
                    LabelPojo labelPojo = new LabelPojo();
                    BeanUtil.copyProperties(item, labelPojo);
                    results.put(item.getId().toString(), JSON.toJSONString(labelPojo));
                });

            }
            return results;
        }catch (Exception e){
            LOG.error("labelAnalysis报错",e);
            return results;
        }
    }
    /**
     * 阶段推进器阶段解析
     * @param fieldAnalysisPojo 字段解析实体类
     * @return java.util.Map<java.lang.String,java.lang.String>
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    public Map<String, String> stageAnalysis(FieldAnalysisPojo fieldAnalysisPojo){
        Integer businessType = fieldAnalysisPojo.getBusinessType();
        if (Objects.equals(businessType, BasicConstant.ZERO)) {
            //少翔：最开始PaaS表单内阶段推进器字段的businessType为0
            businessType = XbbRefTypeEnum.PAAS.getCode();
        }
        StageFindStrategy stageFindStrategy = StageFindFactory.getStageFindStrategy(businessType);
        if (Objects.isNull(stageFindStrategy)) {
            //通用业务增加节点推进器字段（比如合同）
            businessType = XbbRefTypeEnum.PAAS.getCode();
            stageFindStrategy = StageFindFactory.getStageFindStrategy(businessType);
        }
        FieldAttrPojo field = fieldAnalysisPojo.getField();
        Long formId = field.getFormId();
        List<? extends PaasStageEntity> stageList = stageFindStrategy.findStageList(fieldAnalysisPojo.getCorpid(), new StageFindPojo(formId));
        Map<String, String> result = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasStageEntity paasStageEntity : stageList) {
            result.put(paasStageEntity.getCode(), paasStageEntity.getName());
        }
        return result;
    }

    /**
     * 判断字段是否开启百分，如果开启百分比则数据精度需要先加2
     *
     * @param percentUsed 是否开启百分比展示
     * @param accuracy  默认的数据精度
     * @return java.lang.Integer
     * @author zyy
     * @date 2022/8/30
     * @version v1.0
     */
    public static Integer isPercentUsedOfAccuracy(Integer percentUsed, Integer accuracy) {
        return Objects.equals(percentUsed,1) ? accuracy + 2 : accuracy;
    }
}
